package com.global.college.ui.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.global.college.MainActivity;
import com.global.college.R;
import com.global.college.UserData;
import com.global.college.adapter.FreeCourseAdapter;
import com.global.college.adapter.MoreLessonAdapter;
import com.global.college.adapter.StudentItemAdapter;
import com.global.college.base.BaseFragment;
import com.global.college.base.baselist.HnRecyclerGridDecoration;
import com.global.college.data.inner.BannerBean;
import com.global.college.data.net.HomeGoodListBean;
import com.global.college.ui.activity.BottomBarActivity;
import com.global.college.ui.activity.SearchActivity;
import com.global.college.ui.activity.TrainDetailBoughtActivity;
import com.global.college.ui.activity.WebViewActivity;
import com.global.college.ui.banner.OnBannerClickListener;
import com.global.college.ui.bean.UserDataModel;
import com.global.college.ui.interfaces.IHomeSelectView;
import com.global.college.ui.presenter.HomeSelectPresenter;
import com.global.college.utils.LogUtils;
import com.global.college.utils.StringUtils;
import com.global.college.views.RoundCornerImageview;
import com.global.college.views.RoundImageview;
import com.global.college.views.TransformerVideoPager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 精选
 */
public class HomeSelectFragment extends BaseFragment implements IHomeSelectView {
    @BindView(R.id.trans_video)
    TransformerVideoPager banner;
    @BindView(R.id.recycler_free)
    RecyclerView recyclerFree;
    @BindView(R.id.riv_train_cover)
    RoundCornerImageview rivTrainCover;
    @BindView(R.id.tv_train_name)
    TextView tvTrainName;
    @BindView(R.id.tv_train_price)
    TextView tvTrainPrice;
    @BindView(R.id.ll_train)
    LinearLayout llTrain;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.iv_avatar)
    RoundImageview ivAvatar;

    private FreeCourseAdapter freeCourseAdapter;

    private HomeSelectPresenter presenter;

//    private HomeFragment homeFragment;

    private double trainPrice;

    private String trainId;
    private String goodId;//训练营商品id

    /**
     * 轮播图自动轮播消息
     */
    public static final int AUTOBANNER_CODE = 0X1001;
    /**
     * 当前轮播图位置
     */
    private int mBannerPosition;
    /**
     * 自动轮播计时器
     */
    private Timer timer = new Timer();
    /**
     * 自动轮播任务
     */
    private BannerTimerTask mBannerTimerTask;
    /**
     * 用户当前是否点击轮播图
     */
    private boolean mIsUserTouched = false;


    public HomeSelectFragment() {
//        this.homeFragment = homeFragment;
    }

    public void setUserInfo(UserDataModel model) {
        tvUserName.setText(model.getNickName());
        Glide.with(mActivity).load(model.getAvatar()).into(ivAvatar);
    }

    /**
     * 轮播图Handler
     */
    Handler bannerHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            // 当用户点击时,不进行轮播
            if (!mIsUserTouched) {
                // 获取当前的位置
                banner.changeItem();
            }
            return true;
        }
    });

    /**
     * 开始轮播
     */
    private void startBannerTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (mBannerTimerTask != null) {
            mBannerTimerTask.cancel();
        }
        mBannerTimerTask = new BannerTimerTask(bannerHandler);
        if (timer != null && mBannerTimerTask != null) {
            // 循环5秒执行
            timer.schedule(mBannerTimerTask, 4000, 4000);
        }
    }

    public class BannerTimerTask extends TimerTask {
        /**
         * handler
         */
        Handler handler;

        public BannerTimerTask(Handler handler) {
            super();
            this.handler = handler;
        }

        @Override
        public void run() {
            handler.sendEmptyMessage(AUTOBANNER_CODE);
        }
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_home_select;
    }

    @Override
    public void initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        presenter = new HomeSelectPresenter(mActivity);
        presenter.setISelectView(this);
        initBanner();
    }

    private void initBanner() {
        BannerBean bean1 = new BannerBean(R.drawable.home_banner_train, "1");
        BannerBean bean3 = new BannerBean(R.drawable.home_banner, trainId);
        List<BannerBean> beanList = new ArrayList<>();
        beanList.add(bean1);
        beanList.add(bean3);
//        beanList.add(bean3);
        banner.initAdapter(new OnBannerClickListener() {
            @Override
            public void onBannerClick(String trainId) {
                if (!StringUtils.isEmpty(trainId) && trainId.equals("1")) {
                    //不跳转
                } else if (StringUtils.isEmpty(trainId)) {
                    startActivity(new Intent(mActivity, WebViewActivity.class)
                            .putExtra("url", "http://h5.uton.net/recruitActivity").putExtra("title", "活动详情"));
                } else {
                    jumpTrain();
                }
            }
        });
        banner.setDatas(beanList, 0);
        startBannerTimer();
        banner.setScrollSpeed();
    }

    @Override
    protected void initData() {
        presenter.getTrain();
        presenter.getFreeCourse();
    }

    @OnClick({R.id.tv_input,R.id.tv_more_free, R.id.ll_train})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_input:
                SearchActivity.actionStart(mActivity);
                break;
            case R.id.tv_more_free:
                ((MainActivity) mActivity).jump2Course();
                break;
            case R.id.ll_train:
                jumpTrain();
                break;
            default:
                break;
        }
    }

    public void jumpTrain() {
        //免费商品直接跳转已购买训练营页面，同时创建订单
        if (trainPrice == 0d) {
            presenter.createOrder(UserData.getInstance().getUserId(), goodId);
            mActivity.startActivity(new Intent(mActivity, TrainDetailBoughtActivity.class).putExtra("trainId", trainId));
        } else {
            //收费商品判断是否已购买
            presenter.getTrainDetail(trainId, goodId,("￥" + String.format("%.2f", trainPrice)));
        }
    }

    @Override
    public void onGetTrain(HomeGoodListBean beans) {
        tvTrainName.setText(beans.getGoodList().get(0).getGoodName());
        trainPrice = beans.getGoodList().get(0).getGoodPrice() - beans.getGoodList().get(0).getGoodPreferentialPrice();
        tvTrainPrice.setText("￥" + String.format("%.2f", trainPrice));
        goodId = beans.getGoodList().get(0).getGoodId();
        if (beans.getGoodList().get(0).getTrainingModel() == null) {
            LogUtils.i("未获取到训练营信息");
            return;
        }
        Glide.with(mActivity).load(beans.getGoodList().get(0).getTrainingModel().getCover()).into(rivTrainCover);
        ((MainActivity) getActivity()).setCourseCover(beans.getGoodList().get(0).getTrainingModel().getCover());
        trainId = beans.getGoodList().get(0).getTrainingModel().getTrainingId();
        presenter.getIsbought(trainId);
        initBanner();
//        homeFragment.onGetTrain(beans);
    }

    @Override
    public void onGetCourse(HomeGoodListBean bean) {
        if (freeCourseAdapter == null) {
            freeCourseAdapter = new FreeCourseAdapter();
            if (bean.getGoodList().size() == 0) {
                return;
            }
//            StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(listSize, StaggeredGridLayoutManager.HORIZONTAL);
//            recyclerFree.setLayoutManager(layoutManager);
            //设置为每行两列的列表
            recyclerFree.setLayoutManager(new GridLayoutManager(mActivity, 2));
            recyclerFree.addItemDecoration(new HnRecyclerGridDecoration(12));
            freeCourseAdapter.bindToRecyclerView(recyclerFree);
        }
        freeCourseAdapter.addData(bean.getGoodList());
    }

    @Override
    public void onGetBought(boolean isBought) {
        if (!isBought) {
//            homeFragment.setVisible();
        }
    }
}
